﻿using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Threading;
using System;

namespace nRoute.Samples.Sudoku.Behaviors
{
    public class DelayTrigger
        : TriggerBase<FrameworkElement>
    {

        public static readonly DependencyProperty DelayDurationProperty =
            DependencyProperty.Register("DelayDuration", typeof(Duration), typeof(DelayTrigger),
            new PropertyMetadata(Duration.Forever));

        private DispatcherTimer _timer;

        [Category("Common Properties")]
        public Duration DelayDuration
        {
            get { return (Duration) this.GetValue(DelayDurationProperty);  }
            set { this.SetValue(DelayDurationProperty, value);}
        }

#region Overrides

        protected override void OnAttached()
        {
            base.OnAttached();
            if (this.DelayDuration == Duration.Forever) return;

            _timer = new DispatcherTimer();
            _timer.Interval = DelayDuration.TimeSpan;
            _timer.Tick += new EventHandler(Timer_Tick);
            _timer.Start();
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            if (_timer == null) return;

            if (_timer.IsEnabled) _timer.Stop();
            _timer.Tick -= new EventHandler(Timer_Tick);
            _timer = null;
        }

#endregion

#region Handlers

        void Timer_Tick(object sender, System.EventArgs e)
        {
            _timer.Stop();
            _timer.Tick -= new EventHandler(Timer_Tick);
            _timer = null;
            this.InvokeActions(DelayDuration);
        }

#endregion

    }
}
